package com.dongdongshop.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdongsop.data.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Controller
@RequestMapping("fileController")
public class FileController {

    @RequestMapping("upLoadFile")
    @ResponseBody
    public AjaxResult upLoadFile(@RequestParam("image") MultipartFile image){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String https = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI9UKh1mnyfDdp";
        String accessKeySecret = "NdKILCD1iiy5FOlEVudIk56KDuNdl3";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dongdongshop--2109";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/"+image.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(https+endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName,image.getInputStream());
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(https).append(bucketName).append(".").append(endpoint).append("/").append(objectName);
        return AjaxResult.OK().setData(buffer.toString());
    }
}
